package com.znzz.course.util;

import android.os.Handler;
import android.os.Message;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 * 网络连接工具
 * 通过该方法去连接我的后端数据库服务器
 */
public class ConnByHttp extends Thread {
    String new_url;
    Handler handler;
    public ConnByHttp(String url, Handler handler){
        this.new_url = url;
        this.handler  =handler;
    }
    @Override
    public void run() {
        super.run();
        //1.创建客户端,指定需要访问的服务器网址
        try {
            URL url=new URL(new_url);
            //2.创建连接对象
            URLConnection connection=url.openConnection();
            //3.发起连接请求
            connection.connect();
            //4.获取响应数据
            BufferedReader br=new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String content=null;
            DataInputStream dis = new DataInputStream(connection.getInputStream());
            content = dis.readUTF();
            System.out.println("content="+content);
            //将接收到的数据传递给UI线程
            Message msg = new Message();
            msg.what = 1;
            msg.obj = content;
            handler.sendMessage(msg);

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
